package com.alex.ip.holder.server.api;

import cn.hutool.core.bean.BeanUtil;
import com.alex.ip.holder.common.dto.ClientDTO;
import com.alex.ip.holder.common.enums.AlexResult;
import com.alex.ip.holder.common.vo.ClientVO;
import com.alex.ip.holder.server.service.ClientService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 客戶端管理
 *
 * @author Alex.Liu
 * @date: 2025-02-18 15:22
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/client")
public class ClientApi {

    @Resource
    private ClientService clientService;

    /**
     * 服務註冊
     *
     * @param request   请求
     * @param clientDTO 服务元数据
     * @return
     */
    @RequestMapping(value = "register", method = {RequestMethod.GET, RequestMethod.POST})
    public String register(HttpServletRequest request, @RequestBody ClientDTO clientDTO) {
        try {
            String host = request.getRemoteAddr();
            ClientVO bean = BeanUtil.toBean(clientDTO, ClientVO.class);
            bean.setHost(host);
            bean.setLastUpdateTime(System.currentTimeMillis());
            if (log.isDebugEnabled()) {
                log.debug("客戶端註冊:{}", bean);
            }
            return clientService.register(bean);
        } catch (Exception e) {
            log.error("服务报送失败:{}", clientDTO, e);
            return AlexResult.ERROR.name();
        }
    }

}
